package com.sskj.level.ui.fragment;


import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.sskj.common.adapter.ItemClickSupport;
import com.sskj.common.adapter.slimadapter.IViewInjector;
import com.sskj.common.adapter.slimadapter.SlimAdapter;
import com.sskj.common.adapter.slimadapter.SlimInjector;
import com.sskj.common.base.App;
import com.sskj.level.R;
import com.sskj.level.R2;
import com.sskj.level.presenter.FiveFragmentPresenter;
import com.sskj.level.util.CoinUtil;
import com.sskj.lib.RConfig;
import com.sskj.lib.RxBusCode;
import com.sskj.lib.base.BaseFragment;
import com.sskj.lib.bean.CoinBean;
import com.sskj.lib.bean.LevelCoinType;
import com.sskj.lib.bean.WSFiveBean;
import com.sskj.lib.bean.enums.ColorEnum;
import com.sskj.lib.box.LiveDataBus;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import butterknife.BindView;

@Route(path = RConfig.LEVEL_FRAGMENT_FIVE)
public class FiveFragment extends BaseFragment<FiveFragmentPresenter> {
    @BindView(R2.id.sellRecyclerView)
    RecyclerView sellRecyclerView;
    @BindView(R2.id.buyRecyclerView)
    RecyclerView buyRecyclerView;
    @BindView(R2.id.loadingLayout)
    FrameLayout loadingLayout;
    @BindView(R2.id.tvPrice)
    TextView tvPrice;
    @BindView(R2.id.tvRMB)
    TextView tvRMB;
    @BindView(R2.id.top)
    LinearLayout top;
    private SlimAdapter<WSFiveBean.FiveBean> sellSlimAdapter;
    private SlimAdapter<WSFiveBean.FiveBean> buySlimAdapter;
    @Autowired
    String code;
    private int flag = 0;

    @Override
    protected int getLayoutId() {
        return R.layout.level_fragment_five;
    }

    @Override
    public FiveFragmentPresenter getPresenter() {
        return new FiveFragmentPresenter();
    }

    @Override
    public void initView() {
        ARouter.getInstance().inject(this);
        initFive();
    }

    @Override
    public void initData() {
        mPresenter.getPankou(code);
        mPresenter.initSocket(code);

        loadingLayout.setVisibility(View.GONE);

        LiveDataBus.get().with(RxBusCode.PUSH_PANKOU, WSFiveBean.class)
                .observe(this, this::updateFive);

        LiveDataBus.get().with(RxBusCode.PUSH_COIN_BEAN_LEVEL, CoinBean.class)
                .observe(this, this::updatePrice);
        LiveDataBus.get().with(RxBusCode.LEVEL_CHANGE_COIN, LevelCoinType.class)
                .observe(this, this::refresh);
    }

    @SuppressWarnings("unchecked")
    private void initFive() {
        sellRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, true));
        buyRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        buySlimAdapter = SlimAdapter.create().register(R.layout.level_recy_item_pankou, new SlimInjector<WSFiveBean.FiveBean>() {
            @Override
            public void onInject(WSFiveBean.FiveBean data, IViewInjector injector, List<Object> payloads) {
                injector.text(R.id.tvOrderNum, buySlimAdapter.getData().indexOf(data) + 1 + "")
                        .text(R.id.tvPrice, data.getPrice() == null ? "--" : data.getPrice())
                        .textColor(R.id.tvPrice, ContextCompat.getColor(App.INSTANCE, R.color.levelGreen))
                        .text(R.id.tvNum,data.getTotalSize())
                        .with(R.id.bibiProgressbar, view -> {
                            ProgressBar progressBar = (ProgressBar) view;
                            progressBar.setProgressDrawable(ContextCompat.getDrawable(App.INSTANCE, R.drawable.level_progress_green));
                            progressBar.setProgress(100 - data.getPercent());
                        });

            }
        }).attachTo(buyRecyclerView).updateData(new ArrayList());
        sellSlimAdapter = SlimAdapter.create().register(R.layout.level_recy_item_pankou, new SlimInjector<WSFiveBean.FiveBean>() {
            @Override
            public void onInject(WSFiveBean.FiveBean data, IViewInjector injector, List<Object> payloads) {
//                injector.text(R.id.tvOrderNum, sellSlimAdapter.getData().size() - (sellSlimAdapter.getData().indexOf(data)) + "")
                injector.text(R.id.tvOrderNum, sellSlimAdapter.getData().indexOf(data) + 1 + "")
                        .textColor(R.id.tvPrice, ContextCompat.getColor(App.INSTANCE, R.color.levelRed))
                        .text(R.id.tvPrice, data.getPrice() == null ? "--" :  data.getPrice())
                        .text(R.id.tvNum, data.getTotalSize())
                        .with(R.id.bibiProgressbar, view -> {
                            ProgressBar progressBar = (ProgressBar) view;
                            progressBar.setProgressDrawable(ContextCompat.getDrawable(App.INSTANCE, R.drawable.level_progress_red));
                            progressBar.setProgress(100 - data.getPercent());
                        });
            }
        }).attachTo(sellRecyclerView).updateData(new ArrayList());

        ItemClickSupport.addTo(buyRecyclerView)
                .setOnItemClickListener((recyclerView, i, view) -> {
                    if (i < 0) {
                        return;
                    }
                    WSFiveBean.FiveBean dataItem = buySlimAdapter.getDataItem(i);
                    LiveDataBus.get().with(RxBusCode.CHANGE_PRICE, String.class)
                            .postValue(dataItem.getPrice());
                });
        ItemClickSupport.addTo(sellRecyclerView)
                .setOnItemClickListener((recyclerView, i, view) -> {
                    if (i < 0) {
                        return;
                    }
                    WSFiveBean.FiveBean dataItem = sellSlimAdapter.getDataItem(i);
                    LiveDataBus.get().with(RxBusCode.CHANGE_PRICE, String.class)
                            .postValue(dataItem.getPrice());


                });

    }


    public void refresh(LevelCoinType coinType) {
        code = coinType.getCode();
        mPresenter.sendCode(code);
        mPresenter.getPankou(code);
        resetFiveUI();
    }

    public void updatePrice(CoinBean coinBean) {
        if (coinBean.getCode().equalsIgnoreCase(code)) {
            tvPrice.setText(CoinUtil.keepCoinPrice(code, coinBean.getPrice()));
            tvPrice.setTextColor(ColorEnum.getColor(coinBean.isUp()));
            tvRMB.setText("≈" + coinBean.getCnyPrice() + " CNY");
        }
    }


    public void updateFive(WSFiveBean wsFiveBean) {
        int listLong = 8;
//        if (flag == 0) {
//            listLong = 5;
//        } else if (flag == 1) {
//            listLong = 10;
//        } else if (flag == 2) {
//            listLong = 50;
//        }
        if (wsFiveBean.getCode().equalsIgnoreCase(code)) {
            Collections.sort(wsFiveBean.getAsks(), (o1, o2) -> {
                try {
                    return new BigDecimal(o1.getPrice()).doubleValue() > new BigDecimal(o2.getPrice()).doubleValue() ? -1 : 1;
                } catch (Exception e) {
                    return 1;
                }
            });
            Collections.sort(wsFiveBean.getBids(), (o1, o2) -> {
                try {
                    return new BigDecimal(o1.getPrice()).doubleValue() > new BigDecimal(o2.getPrice()).doubleValue() ? -1 : 1;
                } catch (Exception e) {
                    return 1;
                }
            });
            if (wsFiveBean.getAsks().size() > listLong) {
                int startIndex = wsFiveBean.getAsks().size() - listLong;
                wsFiveBean.setAsks(wsFiveBean.getAsks().subList(startIndex, wsFiveBean.getAsks().size()));
            }
            if (wsFiveBean.getBids().size() > listLong) {
                wsFiveBean.setBids(wsFiveBean.getBids().subList(0, listLong));
            }

            calculatePercentAll(wsFiveBean);
            Collections.reverse(wsFiveBean.getAsks());
            sellSlimAdapter.updateData(wsFiveBean.getAsks());
            buySlimAdapter.updateData(wsFiveBean.getBids());
        }
    }

    private void calculatePercentAll(WSFiveBean wsFiveBean) {
        Double full = 0d;
        for (WSFiveBean.FiveBean bid : wsFiveBean.getBids()) {
            Double aDouble = Double.valueOf(bid.getDoubleTotalSize());
            if (aDouble > full) {
                full = aDouble;
            }
        }
        for (WSFiveBean.FiveBean ask : wsFiveBean.getAsks()) {
            Double aDouble = Double.valueOf(ask.getDoubleTotalSize());
            if (aDouble > full) {
                full = aDouble;
            }
        }
        for (WSFiveBean.FiveBean bid : wsFiveBean.getBids()) {
            Double aDouble = Double.valueOf(bid.getDoubleTotalSize());
            bid.setPercent((int) (aDouble / full * 100d));
        }

        for (WSFiveBean.FiveBean ask : wsFiveBean.getAsks()) {
            Double aDouble = Double.valueOf(ask.getDoubleTotalSize());
            ask.setPercent((int) (aDouble / full * 100d));
        }

    }

    /**
     * 设置买五卖五UI --
     */
    private void resetFiveUI() {
        WSFiveBean wsFiveBean = new WSFiveBean();
        wsFiveBean.setCode(code);
        ArrayList<WSFiveBean.FiveBean> asks = new ArrayList<>();
        ArrayList<WSFiveBean.FiveBean> bids = new ArrayList<>();
        for (int i = 0; i < 8; i++) {
            asks.add(new WSFiveBean.FiveBean());
            bids.add(new WSFiveBean.FiveBean());
        }
        wsFiveBean.setAsks(asks);
        wsFiveBean.setBids(bids);
        updateFive(wsFiveBean);
    }

}
